import IconButton from '@/components/Icon'
import { Col, Input, Row, Select, Space } from 'antd'
import editOutlined from '@iconify/icons-ant-design/edit-outlined'
import { createPortal } from 'react-dom'
import { useEffect, useState } from 'react'
import ImageLibraryDialog from '@/components/Dialogs/ImageLibraryDialog'
import EditorExecutor from '@/executor/EditorExecutor'
import { getImageSize } from '@/util/FileUtil'
import { mxCell } from 'mxgraph'
import GraphUtil from '@/util/GraphUtil'
import _ from 'lodash'

interface IImageSettingProps {
  cell: mxCell | undefined
}

export default function ImageSetting(props: IImageSettingProps) {
  // 图库对话框的可见状态
  const [imgLibDialogOpen, setImgLibDialogOpen] = useState(false)
  // 当前图片的文件路径
  const [path, setPath] = useState('')

  //当选择了图片
  const onSelectImg = (path: string) => {
    // 获取图片尺寸
    getImageSize(path).then((size) => {
      const { height, width } = size

      EditorExecutor.updateImage(path, height, width)
      // EditorExecutor.setCellStyles('image', path)
      // EditorExecutor.updateCellGeometry('width', width)
      // EditorExecutor.updateCellGeometry('height', height)
      setPath(path)
      setImgLibDialogOpen(false)
    })
  }

  // 当地址发生变化
  const onPathChange = (path: string) => {
    _.debounce((path) => {
      onSelectImg(path)
    }, 1000)
  }

  useEffect(() => {
    if (props.cell) {
      const state = GraphUtil.getSelectionStateForCell(EditorExecutor.graph, props.cell)
      const { style } = state
      setPath(style.image)
    } else {
      setPath('')
    }
  }, [props.cell])

  return (
    <>
      <Space direction="vertical" size="small" style={{ display: 'flex' }}>
        <Row>
          <Col span={10} className="label">
            图片
          </Col>
        </Row>

        <Row gutter={5}>
          <Col span={4}>路径</Col>
          <Col span={17}>
            <Input.TextArea value={path} onChange={(e) => onPathChange(e.target.value)} rows={5} />
          </Col>
          <Col span={3}>
            <IconButton
              icon={editOutlined}
              tip=""
              // className="h-24px w-40px! "
              fontSize={15}
              onClick={() => setImgLibDialogOpen(true)}
            />
          </Col>
        </Row>
      </Space>
      {imgLibDialogOpen &&
        createPortal(
          <ImageLibraryDialog
            onClose={() => setImgLibDialogOpen(false)}
            onOk={(url) => {
              onSelectImg(url)
            }}
          />,
          document.body
        )}
    </>
  )
}
